<script setup>
import AppCardCode from '@/views/liteflow/logic/AppCardCode.vue';
import FlowChart from '@/views/liteflow/logic/FlowChart.vue';
import { ref } from 'vue';
import { VDataTableServer } from 'vuetify/labs/VDataTable';

// 表头
const headers = [
  {
    title: '表达式ID',
    key: 'elId',
  },
  {
    title: '表达式名称',
    key: 'elName',
  },
  {
    title: '执行器',
    key: 'executorId',
  },
  {
    title: 'EL表达式',
    key: 'el',
  },
  {
    title: '操作',
    key: 'actions',
    sortable: false,
  },
]

const pageUrl = ref(API_URLS.lfElPage)
const deleteUrl = ref(API_URLS.lfElDelete)
const addUrl = ref(API_URLS.lfElAdd)
const updateUrl = ref(API_URLS.lfElUpdate)
const elId = ref()
const elName = ref()
const executorId = ref()
const el = ref()

onMounted(() => {
  executorOptionQuery()
})

const executorOptions = reactive([])

const executorOptionQuery = async () => {
  const res = await $ivyApi.post(API_URLS.lfExecutorOptions,{})
  executorOptions.push(...res.data)
}

// 分页列表
const totalPage = ref(1)
const totalRows = ref(0)
const list = ref([])
const loadings = ref(false)

// 分页参数
const options = ref({
  page: 1,
  itemsPerPage: 10,
  sortBy: [],
  groupBy: [],
  search: undefined,
})

const fetchList = async (msg) => {
  loadings.value = true
  const res = await $ivyApi.post(pageUrl.value,{
    elName: elName.value,
    elId: elId.value,
    executorId: executorId.value,
    el: el.value,
    options: options.value,
  })
  
  const data = res.data
  list.value = data.list
  totalPage.value = data.totalPage
  totalRows.value = data.totalRow
  options.value.page = data.page
  loadings.value = false

  if(typeof msg === 'string'){
    res.message = msg
    showMsg(res)
  }
}

watchEffect(fetchList)
// 监听 options 对象的变化，并在变化时调用 fetchList 方法
watch(options, async () => { await fetchList() }, { deep: true })

// 新增&编辑操作
const currRow = ref({})
const operType = ref(-1)
	
const addOper = () => {
  operType.value = 2
  currRow.value = {}
  editVisible.value = true
}

const updateOper = row => {
  operType.value = 3
  currRow.value = row
  editVisible.value = true
}

const editVisible = ref(false)
const editRef = ref(null)

const editCallMethod = () => {
  editVisible.value = false
  editRef.value.saveItem()
  fetchList()
}

const editCancelMethod = () =>{
  editVisible.value = false
  fetchList()
}

const refreshPage = res => {
  showMsg(res)
  fetchList()
}

// 查看
const viewOper = row => {
  currRow.value = row
  elDialogClick()
}


// 删除
const deleteId = ref('')
const deleteVisible = ref(false)

const deleteOper = id => {
  deleteVisible.value = true
  deleteId.value = id
}

// 确认删除
const deleteAgreeCmp = async (id) => {
  const res = await $ivyApi.post(API_URLS.lfElDelete,{
    id: deleteId.value,
  })

  showMsg(res)
  fetchList()
  deleteVisible.value = false
  deleteId.value = ''
}

// 回调信息
const snackbar = reactive(API_URLS.resultMsg)

const showMsg = res => {
  $resultMsg.show(res,snackbar)
}

// 
const closeFlowChart = () => {
  editVisible.value = false
  fetchList()
}


const resolveExecutorVariant = type => {
  const arr = executorOptions.filter(obj => obj.id == type)
  
  return arr.length != 0 ? arr[0] : null
}

// 调试
const execOper = row => {
  currRow.value = row
  elDialogClick()
}

const isDialogELVisible = ref(false)
const elDialogContent = ref('')
const elExecDialogContent = ref('')
const formatEL = ref(true)

const elDialogClick = async () => {
  isDialogELVisible.value = true
  elDialogContent.value = ''
  elExecDialogContent.value = ''

  const res = await $ivyApi.post(API_URLS.lfElBuild, {
    json: currRow.value.flowJson,
    formatEL: formatEL.value,
  })

  elDialogContent.value = { 'js': res.data }
}

const elExecDialogClick = async () => {
  elExecDialogContent.value = ''

  const res = await $ivyApi.post(API_URLS.lfElExec, {
    json: currRow.value.flowJson,
  })

  elExecDialogContent.value = { 'js': res.data }
}

watch(formatEL, () =>{
  elDialogClick()
})
</script>

<template>
  <section>
    <VRow>
      <VSnackbar
        v-model="snackbar.msgVisible"
        location="top"
        :color="snackbar.msgColor"
      >
        {{ snackbar.msgContent }}
      </VSnackbar>

      <VCol cols="12">
        <VCard title="">
          <VCardText>
            <VRow>
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="elId"
                  label="表达式ID"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="4"
              >
                <VTextField
                  v-model="elName"
                  label="表达式名称"
                  clearable
                />
              </VCol>
              <VCol
                cols="12"
                sm="4"
              >
              <VAutocomplete
                  v-model="executorId"
                  label="执行器"
                  :items="executorOptions"
                  clearable
                  item-title="executorName"
                  item-value="id"
                />
              </VCol>
            </VRow>
          </VCardText>

          <VDivider />

          <VCardText class="d-flex flex-wrap py-4 gap-4">
            <div class="me-3 d-flex gap-3">
              <AppSelect
                :model-value="options.itemsPerPage"
                :items="[
                  { value: 10, title: '10' },
                  { value: 20, title: '20' },
                  { value: 50, title: '50' },
                  { value: 100, title: '100' },
                ]"
                style="inline-size: 6.25rem;"
                @update:model-value="options.itemsPerPage = parseInt($event, 10)"
              />
            </div>
            <VSpacer />

            <div class="d-flex align-center flex-wrap gap-4">
              <VBtn
                :loading="loadings"
                :disabled="loadings"
                size="38"
                @click="fetchList('刷新成功')"
              >
                <VIcon
                  icon="tabler-refresh"
                  size="22"
                />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  刷新
                </VTooltip>
              </VBtn>
              <VBtn
                prepend-icon="tabler-plus"
                @click="addOper"
              >
                新增
              </VBtn>
            </div>
          </VCardText>

          <VDivider />

          <VDataTableServer
            v-model:items-per-page="options.itemsPerPage"
            v-model:page="options.page"
            :items="list"
            :items-length="totalRows"
            :headers="headers"
            class="text-no-wrap"
            @update:options="options = $event"
          >
            <template #item.elId="{ item }">
              <span class="font-weight-medium">{{ item.elId }}</span>
            </template>

            <template #item.elName="{ item }">
              <span class="font-weight-medium">{{ item.elName }}</span>
            </template>

            <template #item.el="{ item }">
              <span class="font-weight-medium">
                <VBtn
                  variant="plain"
                  size="small"
                  style="padding-inline-start: 0;"
                >
                  查看
                  <VTooltip
                    activator="parent"
                    location="top"
                  >
                    <span v-html="item.el" />
                  </VTooltip>
                </VBtn>
              </span>
            </template>
            
            <template #item.executorId="{ item }">
              <VChip
                color="primary"
                class="font-weight-medium"
                size="small"
                v-if="resolveExecutorVariant(item.executorId)"
              >
                {{ resolveExecutorVariant(item.executorId).executorName }}
              </VChip>
            </template>

            <template #item.actions="{ item }">
              <IconBtn color="error" @click="deleteOper(item.id)">
                <VIcon icon="tabler-trash" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  删除
                </VTooltip>
              </IconBtn>

              <IconBtn @click="updateOper(item)">
                <VIcon icon="tabler-edit" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  编辑
                </VTooltip>
              </IconBtn>

              <IconBtn @click="execOper(item)">
                <VIcon icon="tabler-player-play-filled" />
                <VTooltip
                  activator="parent"
                  location="top"
                >
                  调试
                </VTooltip>
              </IconBtn>
            </template>

            <!-- pagination -->
            <template #bottom>
              <VDivider />
              <div class="d-flex align-center justify-sm-space-between justify-center flex-wrap gap-3 pa-5 pt-3">
                <p class="text-sm text-disabled mb-0">
                  共<span style="color: #7367f0;">&nbsp;{{ totalRows }}&nbsp;</span>条记录
                </p>
                <VPagination
                  v-model="options.page"
                  :length="Math.ceil(totalRows / options.itemsPerPage)"
                  :total-visible="$vuetify.display.xs ? 1 : Math.ceil(totalRows / options.itemsPerPage)"
                >
                  <template #prev="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      上一页
                    </VBtn>
                  </template>

                  <template #next="slotProps">
                    <VBtn
                      variant="tonal"
                      color="default"
                      v-bind="slotProps"
                      :icon="false"
                    >
                      下一页
                    </VBtn>
                  </template>
                </VPagination>
              </div>
            </template>
          </VDataTableServer>
          <!-- SECTION -->
        </VCard>

        <VDialog
          v-model="editVisible"
          fullscreen
          :scrim="false"
          transition="dialog-bottom-transition"
        >
          <VCard>
            <div v-if="false">
              <VToolbar color="primary">
                <VBtn
                  icon
                  variant="plain"
                  @click="editVisible = false"
                >
                  <VIcon
                    color="white"
                    icon="tabler-x"
                  />
                </VBtn>

                <VToolbarTitle>设置</VToolbarTitle>

                <VSpacer />

                <VToolbarItems>
                  <VBtn
                    variant="text"
                    @click="editCancelMethod"
                  >
                    取消
                  </VBtn>
                  <VBtn
                    variant="text"
                    @click="editCallMethod"
                  >
                    保存
                  </VBtn>
                </VToolbarItems>
              </VToolbar>
            </div>
            <div style="padding: 12px;block-size: 100%;">
              <FlowChart @closeFlowChart="closeFlowChart" :operType="operType" :curr-row="currRow" />
            </div>
          </VCard>
        </VDialog>

        <!-- 查看EL表达式 -->
        <VDialog
          v-model="isDialogELVisible"
          scrollable
          width="800"
          class="ivy-dialog"
        >
          <DialogCloseBtn @click="isDialogELVisible = !isDialogELVisible" />
        
          <VCard>
            <VCardItem class="pb-5">
              <VCardTitle>EL表达式</VCardTitle>
            </VCardItem>
            <VDivider />
            <VCardText>
              <div class="button-group">
                <VBtn
                  size="small"
                  @click="formatEL = true"
                >
                  格式化数据
                </VBtn>
                <VBtn
                  size="small"
                  @click="formatEL = false"
                >
                  非格式化数据
                </VBtn>
              </div>
              <AppCardCode
                title=""
                code-language="js"
                :code="elDialogContent"
                no-padding
                show-code
                :show-title="false"
              />
              <VBtn
                size="small"
                @click="elExecDialogClick"
              >
                执行EL表达式
              </VBtn>
            
              <AppCardCode
                title=""
                code-language="js"
                :code="elExecDialogContent"
                no-padding
                show-code
                :show-title="false"
                class="el-code"
              />
            </VCardText>
          </VCard>
        </VDialog>
        
        <!-- 删除确认 -->
        <VDialog
          v-model="deleteVisible"
          width="300"
        >
          <DialogCloseBtn @click="deleteVisible = !deleteVisible" />
          <VCard title="提示">
            <VCardText> 是否确认删除？ </VCardText>
            <VCardText class="d-flex justify-end gap-3 flex-wrap">
              <VBtn
                color="secondary"
                variant="tonal"
                @click="deleteVisible = false"
              >
                取消
              </VBtn>
              <VBtn @click="deleteAgreeCmp">
                确定
              </VBtn>
            </VCardText>
          </VCard>
        </VDialog>
      </vcol>
    </vrow>
  </section>
</template>

<style lang="scss">
.text-capitalize {
  text-transform: capitalize;
}

.user-list-name:not(:hover) {
  color: rgba(var(--v-theme-on-background), var(--v-medium-emphasis-opacity));
}

.button-group button {
  margin-block: 8px;
  margin-inline-end: 8px;
}
</style>
